import config from '../config/sub-module'
import router from './index'

const subModules = Object.keys(config)
/**
 * 是否含有子模块
 * @param {string} moduleKey 
 */
function hasSubModules (moduleKey) {
  return subModules.indexOf(moduleKey) > -1
}
/**
 * 是否已加载子模块
 * @param {string} moduleKey 
 */
function hasLoadSubModules (moduleKey) {
  return !!window[moduleKey]
}
/**
 * 加载子模块
 * @param {string} moduleKey 
 */
function loadSubModule (moduleKey) {
  const mdConfig = config[moduleKey]
  window.__POWER_PATH__ = mdConfig.baseUrl
  return new Promise((resolve) => {
    const css = document.createElement('link')
    css.setAttribute('rel', 'stylesheet')
    css.setAttribute('href', mdConfig.baseUrl + mdConfig.css)
    css.setAttribute('type', 'text/css')
    document.head.appendChild(css)
    const script = document.createElement('script')
    script.src = mdConfig.baseUrl + mdConfig.js
    document.body.appendChild(script)
    script.onload = () => {
      router.addRoutes(window[moduleKey].router)
      resolve()
    }
  })
}
export {
  subModules,
  hasSubModules,
  hasLoadSubModules,
  loadSubModule
}
